#!/bin/bash
# 简化测试数据生成脚本 - 仅生成必要数据用于演示
# 包含：1个user1 + 3位教师（语文/数学/英语）+ 4个班级 + 随机课表

echo "🎯 生成简化演示数据"

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

SERVER_URL="http://47.108.201.156"

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查服务器状态
check_server() {
    log_step "检查服务器状态..."
    
    response=$(curl -s -w "%{http_code}" -o /dev/null "$SERVER_URL/admin/users")
    
    if [ "$response" == "200" ]; then
        log_info "✅ 服务器运行正常"
    else
        log_error "❌ 服务器无法访问，HTTP状态: $response"
        exit 1
    fi
}

# 清空数据库所有数据
clear_all_data() {
    log_step "清空数据库所有数据..."
    
    # 删除所有班级（会级联删除相关数据）
    classes_response=$(curl -s "$SERVER_URL/admin/classes")
    if command -v jq >/dev/null 2>&1; then
        echo "$classes_response" | jq -r '.classes[].ID' | while read class_id; do
            if [ -n "$class_id" ]; then
                log_info "删除班级 ID: $class_id"
                curl -s -X DELETE "$SERVER_URL/admin/classes/$class_id" > /dev/null
            fi
        done
    fi
    
    # 删除所有用户
    users_response=$(curl -s "$SERVER_URL/admin/users")
    if command -v jq >/dev/null 2>&1; then
        echo "$users_response" | jq -r '.users[].userID' | while read user_id; do
            if [ -n "$user_id" ]; then
                log_info "删除用户 ID: $user_id"
                curl -s -X DELETE "$SERVER_URL/admin/users/$user_id" > /dev/null
            fi
        done
    fi
    
    log_info "✅ 数据库清空完成"
}

# 创建基础用户
create_basic_users() {
    log_step "创建基础用户..."
    
    # 创建user1
    user1='{"userID": "1000000001", "username": "user1", "password": "user123", "userType": "user"}'
    curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "$user1" \
        "$SERVER_URL/admin/users" > /dev/null
    log_info "✅ 创建用户: user1"
    
    # 创建3位教师
    teachers=(
        '{"userID": "2000000001", "username": "teacher_chinese", "password": "teacher123", "userType": "teacher"}'
        '{"userID": "2000000002", "username": "teacher_math", "password": "teacher123", "userType": "teacher"}'
        '{"userID": "2000000003", "username": "teacher_english", "password": "teacher123", "userType": "teacher"}'
    )
    
    for teacher in "${teachers[@]}"; do
        curl -s -X POST \
            -H "Content-Type: application/json" \
            -d "$teacher" \
            "$SERVER_URL/admin/users" > /dev/null
    done
    
    log_info "✅ 创建3位教师: teacher_chinese, teacher_math, teacher_english"
}

# 生成随机课表数据（7天x4节课，每周20节课）
generate_random_schedule() {
    local class_name="$1"
    local class_type="$2"
    
    # 定义科目池
    local subjects=()
    case "$class_type" in
        "chinese_focus")
            subjects=("Chinese" "Chinese Literature" "English" "Mathematics" "History" "Geography" "Physics" "Chemistry" "Biology" "Art" "Music" "Physical Education" "Computer Science" "Economics" "Politics" "Philosophy" "Psychology" "Sociology" "Ethics" "Research Methods")
            ;;
        "math_focus")
            subjects=("Mathematics" "Advanced Mathematics" "English" "Chinese" "Physics" "Chemistry" "Biology" "Computer Science" "Statistics" "History" "Geography" "Art" "Music" "Physical Education" "Economics" "Politics" "Philosophy" "Psychology" "Sociology" "Ethics")
            ;;
        "english_focus")
            subjects=("English" "English Literature" "Chinese" "Mathematics" "History" "Geography" "Physics" "Chemistry" "Biology" "Art" "Music" "Physical Education" "Computer Science" "Economics" "Politics" "Philosophy" "Psychology" "Sociology" "Ethics" "Creative Writing")
            ;;
        "balanced")
            subjects=("Chinese" "English" "Mathematics" "Physics" "Chemistry" "Biology" "History" "Geography" "Computer Science" "Art" "Music" "Physical Education" "Economics" "Politics" "Philosophy" "Psychology" "Sociology" "Ethics" "Statistics" "Research Methods")
            ;;
    esac
    
    # 生成7天x4节课的课表，随机分布
    local schedule='['
    for day in {0..6}; do
        schedule+='['
        for period in {0..3}; do
            # 随机选择科目
            local subject_index=$((RANDOM % ${#subjects[@]}))
            local subject="${subjects[$subject_index]}"
            
            schedule+="{\"name\": \"$subject\", \"weekType\": \"continuous\", \"startWeek\": 1, \"endWeek\": 20}"
            
            if [ $period -lt 3 ]; then
                schedule+=','
            fi
        done
        schedule+=']'
        if [ $day -lt 6 ]; then
            schedule+=','
        fi
    done
    schedule+=']'
    
    echo "$schedule"
}

# 创建4个班级的课表
create_class_schedules() {
    log_step "创建4个班级的随机课表..."
    
    local classes=(
        "2023240501:chinese_focus"
        "2023240502:math_focus" 
        "2023240503:english_focus"
        "2023240504:balanced"
    )
    
    for class_info in "${classes[@]}"; do
        local class_name="${class_info%:*}"
        local class_type="${class_info#*:}"
        
        log_info "生成班级 $class_name ($class_type) 的课表..."
        
        local schedule_data=$(generate_random_schedule "$class_name" "$class_type")
        
        local class_schedule="{
            \"className\": \"$class_name\",
            \"schedule\": $schedule_data
        }"
        
        response=$(curl -s -X POST \
            -H "Content-Type: application/json" \
            -d "$class_schedule" \
            "$SERVER_URL/api/schedule/save")
        
        if echo "$response" | grep -q "successfully"; then
            log_info "✅ 创建班级 $class_name 课表成功"
        else
            log_error "❌ 创建班级 $class_name 课表失败: $response"
        fi
    done
}

# 为教师分配授课时间
assign_teacher_schedules() {
    log_step "为教师分配授课时间..."
    
    # 语文教师 - 在不同班级教授不同科目
    assign_teacher_to_class "2000000001" "2023240501" "Chinese" "Chinese Literature"
    assign_teacher_to_class "2000000001" "2023240502" "Chinese" "History"
    assign_teacher_to_class "2000000001" "2023240503" "Chinese" "Philosophy"
    assign_teacher_to_class "2000000001" "2023240504" "Chinese" "Ethics"
    
    # 数学教师 - 在不同班级教授不同科目
    assign_teacher_to_class "2000000002" "2023240501" "Mathematics" "Statistics"
    assign_teacher_to_class "2000000002" "2023240502" "Mathematics" "Advanced Mathematics"
    assign_teacher_to_class "2000000002" "2023240503" "Mathematics" "Computer Science"
    assign_teacher_to_class "2000000002" "2023240504" "Mathematics" "Physics"
    
    # 英语教师 - 在不同班级教授不同科目
    assign_teacher_to_class "2000000003" "2023240501" "English" "English Literature"
    assign_teacher_to_class "2000000003" "2023240502" "English" "Creative Writing"
    assign_teacher_to_class "2000000003" "2023240503" "English" "English Literature"
    assign_teacher_to_class "2000000003" "2023240504" "English" "Research Methods"
}

# 为单个教师分配班级授课时间
assign_teacher_to_class() {
    local teacher_id="$1"
    local class_name="$2"
    local subject1="$3"
    local subject2="$4"
    
    # 生成随机时间槽位（每周5个时间槽）
    local slots='['
    for i in {1..5}; do
        local row=$((RANDOM % 7))  # 0-6天
        local col=$((RANDOM % 4))  # 0-3节课
        
        slots+="{\"row\": $row, \"col\": $col}"
        if [ $i -lt 5 ]; then
            slots+=','
        fi
    done
    slots+=']'
    
    local plan_data="{
        \"teacherId\": \"$teacher_id\",
        \"className\": \"$class_name\",
        \"weeks\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
        \"slots\": $slots
    }"
    
    response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "$plan_data" \
        "$SERVER_URL/api/teacher/teach-schedule/overwrite-batch")
    
    if echo "$response" | grep -q "saved"; then
        log_info "✅ 教师 $teacher_id 分配到班级 $class_name"
    else
        log_warn "⚠️ 教师 $teacher_id 分配到班级 $class_name 可能失败: $response"
    fi
}

# 验证生成的数据
verify_data() {
    log_step "验证生成的数据..."
    
    # 检查用户数量
    users_response=$(curl -s "$SERVER_URL/admin/users")
    if command -v jq >/dev/null 2>&1; then
        user_count=$(echo "$users_response" | jq -r '.users | length')
        log_info "✅ 总用户数: $user_count"
        
        # 显示用户类型分布
        admin_count=$(echo "$users_response" | jq -r '[.users[] | select(.userType=="admin")] | length')
        teacher_count=$(echo "$users_response" | jq -r '[.users[] | select(.userType=="teacher")] | length')
        user_type_count=$(echo "$users_response" | jq -r '[.users[] | select(.userType=="user")] | length')
        
        log_info "  管理员: $admin_count, 教师: $teacher_count, 学生: $user_type_count"
    fi
    
    # 检查班级数量
    classes_response=$(curl -s "$SERVER_URL/admin/classes")
    if command -v jq >/dev/null 2>&1; then
        class_count=$(echo "$classes_response" | jq -r '.classes | length')
        log_info "✅ 总班级数: $class_count"
        
        # 显示班级列表
        echo "$classes_response" | jq -r '.classes[] | "  - \(.name) (ID: \(.ID))"'
    fi
}

# 显示演示账户信息
show_demo_info() {
    log_step "显示演示账户信息..."
    
    echo ""
    echo "========================================"
    echo "🎯 简化演示数据信息"
    echo "========================================"
    echo ""
    echo "👤 学生账户:"
    echo "  用户名: user1"
    echo "  密码: user123"
    echo "  角色: 普通用户"
    echo ""
    echo "👨‍🏫 教师账户:"
    echo "  用户名: teacher_chinese (ID: 2000000001)"
    echo "  密码: teacher123"
    echo "  教授: 语文相关科目"
    echo ""
    echo "  用户名: teacher_math (ID: 2000000002)"
    echo "  密码: teacher123"
    echo "  教授: 数学相关科目"
    echo ""
    echo "  用户名: teacher_english (ID: 2000000003)"
    echo "  密码: teacher123"
    echo "  教授: 英语相关科目"
    echo ""
    echo "📚 班级信息:"
    echo "  - 2023240501 (语文重点班)"
    echo "  - 2023240502 (数学重点班)"
    echo "  - 2023240503 (英语重点班)"
    echo "  - 2023240504 (平衡班)"
    echo ""
    echo "📅 课表特点:"
    echo "  ✓ 每周7天都有课程安排"
    echo "  ✓ 每天4节课，每周20节课"
    echo "  ✓ 课程随机分布，避免紧密排列"
    echo "  ✓ 每个班级的课表安排不同"
    echo "  ✓ 3位教师在不同班级教授不同科目"
    echo ""
    echo "🌐 访问地址: $SERVER_URL:3000"
    echo "========================================"
}

# 主执行流程
main() {
    echo "========================================"
    echo "🎯 简化演示数据生成器"
    echo "📅 生成时间: $(date)"
    echo "🌐 目标服务器: $SERVER_URL"
    echo "========================================"
    
    check_server
    clear_all_data
    create_basic_users
    create_class_schedules
    assign_teacher_schedules
    verify_data
    show_demo_info
    
    echo ""
    log_info "🎉 简化演示数据生成完成！"
    echo ""
    log_info "推荐测试顺序:"
    log_info "1. 使用 user1 登录查看课表"
    log_info "2. 使用 teacher_chinese 登录管理课表"
    log_info "3. 使用 teacher_math 登录管理课表"
    log_info "4. 使用 teacher_english 登录管理课表"
    log_info "5. 测试课程调换、增减功能"
    echo ""
}

# 脚本参数处理
case "${1:-}" in
    "clean")
        log_step "仅清空数据..."
        check_server
        clear_all_data
        log_info "✅ 数据清空完成"
        ;;
    "verify")
        log_step "仅验证数据..."
        check_server
        verify_data
        ;;
    "help"|"-h"|"--help")
        echo "简化演示数据生成器"
        echo ""
        echo "用法:"
        echo "  $0          - 生成完整的演示数据集"
        echo "  $0 clean    - 仅清空现有数据"
        echo "  $0 verify   - 仅验证现有数据"
        echo "  $0 help     - 显示此帮助信息"
        echo ""
        echo "特点:"
        echo "  - 创建1个学生用户(user1)和3位教师"
        echo "  - 生成4个班级(2023240501-2023240504)"
        echo "  - 每周7天x4节课，随机分布课程"
        echo "  - 每个班级课表安排不同"
        echo "  - 3位教师在不同班级教授不同科目"
        echo "  - 适合演示和测试所有功能"
        ;;
    *)
        main
        ;;
esac
